import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:opencv_dart/opencv_dart.dart' as cv;
import 'package:flutter/services.dart' show rootBundle;
import 'package:opencv_dart/opencv_dart.dart';

class ImageToContoursPage extends StatefulWidget {
  const ImageToContoursPage({super.key});

  @override
  State<ImageToContoursPage> createState() => _ImageHandlerPageState();
}

class _ImageHandlerPageState extends State<ImageToContoursPage> {
  // 原始图片
  final String originalPath = "assets/images/2.jpeg";
  late Mat originalMat;
  // 转换轮廓
  Uint8List? contourMat;

  Point averagePoint(Point p1, Point p2) {
    return Point((p1.x + p2.x) ~/ 2, (p1.y + p2.y) ~/ 2);
  }

  Point getCenterPoint(List<Point> points, Point currentPoint) {
    for (var point in points) {
      if (point.y == currentPoint.y && point.x != currentPoint.x) {
        return point;
      }
    }
    return Point(0, 0);
  }

  // 图片转轮廓
  void imageToContour(String imagePath) async {
    // 加载图片
    final imageData = await rootBundle.load(imagePath);
    final Uint8List bytes = imageData.buffer.asUint8List();
    originalMat = cv.imdecode(bytes, cv.IMREAD_COLOR);

    // 转换为灰度图像
    final Mat grayMat = cv.cvtColor(originalMat, cv.COLOR_BGR2GRAY);

    // 二值化
    final thresholded = cv.threshold(grayMat, 127, 255, cv.THRESH_BINARY).$2;

    // 高斯模糊
    final Mat blured = cv.gaussianBlur(thresholded, (5, 5), 0);

    // canny边缘检测
    final Mat edges = cv.canny(blured, 50, 150);

    // 查找轮廓
    final contours =
        cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE);

    // 绘制轮廓
    final Mat contourImg =
        Mat.zeros(originalMat.rows, originalMat.cols, cv.MatType.CV_8UC3);
    cv.drawContours(contourImg, contours.$1, -1, Scalar(0, 255, 0),
        thickness: 1);
    // 绘制等间距的填充线
    for (final contour in contours.$1) {
      List<Point> pointList = [];
      for (int i = 0; i < contour.length; i++) {
        pointList.add(contour[i]);
      }

      for (var i = 0; i < contour.length - 1; i++) {
        final p1 = contour[i];
        final p2 = getCenterPoint(pointList, p1);
        print('$p1-$p2');
      }
      cv.line(contourImg, Point(243, 66), Point(262, 66), Scalar(0, 255, 0),
          thickness: 10);
      cv.line(contourImg, Point(141, 162), Point(0, 0), Scalar(0, 255, 0),
          thickness: 10);
      // line(contourImg, contour[i], contour[i + 1], Scalar(0, 255, 0),
      //     thickness: 1);
    }

    // 将 Mat 转换为 Uint8List
    contourMat = cv.imencode('.jpeg', contourImg).$2;
    setState(() {});
  }

  void drawContours() async {
    // 创建一个轮廓
    final List<List<Point>> contours = [
      [Point(50, 50), Point(150, 50), Point(150, 150), Point(50, 150)]
    ];
    // 创建一个 Mat 对象
    final Mat img = Mat.zeros(300, 300, cv.MatType.CV_8UC3);
    // 绘制轮廓
    cv.drawContours(img, contours.cvd, -1, Scalar(255, 0, 255));
    // 将 Mat 转换为 Uint8List
    contourMat = cv.imencode('.jpeg', img).$2;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("image to contour"),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(originalPath, width: 300),
              Padding(
                padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
                child: ElevatedButton(
                  onPressed: () async {
                    imageToContour(originalPath);
                  },
                  child: const Text("image to contour"),
                ),
              ),
              contourMat != null
                  ? Image.memory(
                      contourMat!,
                      width: 300,
                    )
                  : Container(),
            ],
          ),
        ));
  }
}
